package org.example.component;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.example.config.WeChatPayConfig;
import org.example.config.WechatPayApiConfig;
import org.example.vo.PayInfoVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description:
 * @author: 谢超
 * @date: 2024/8/21 10:41
 */
@Component
@Slf4j
public class WechatPayStrategy implements PayStrategy{

    @Resource
    private WeChatPayConfig payConfig;

//    @Resource
//    private CloseableHttpClient wechatPayClient;


    @Override
    public String unifiedOrder(PayInfoVO payInfoVO) {
        //过期时间  RFC 3339格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        //支付订单过期时间
        String timeExpire = sdf.format(new Date(System.currentTimeMillis() + payInfoVO.getOrderPayTimeoutMils()));

        JSONObject amountObj = new JSONObject();
        //数据库存储是double比如，100.99元，微信支付需要以分为单位

        int amount = payInfoVO.getPayFee().multiply(BigDecimal.valueOf(100)).intValue();
        amountObj.put("total", amount);
        amountObj.put("currency", "CNY");

        JSONObject payObj = new JSONObject();
        payObj.put("mchid", payConfig.getMchId());
        payObj.put("out_trade_no", payInfoVO.getOutTradeNo());
        payObj.put("appid", payConfig.getWxPayAppid());
        payObj.put("description", payInfoVO.getTitle());
        payObj.put("notify_url", payConfig.getCallbackUrl());

        payObj.put("time_expire", timeExpire);
        payObj.put("amount", amountObj);
        //回调携带
        payObj.put("attach", "{\"accountNo\":" + payInfoVO.getAccountNo() + "}");

        // 处理请求body参数
        String body = payObj.toJSONString();


        log.debug("请求参数:{}",body);

        StringEntity entity = new StringEntity(body,"utf-8");
        entity.setContentType("application/json");

        HttpPost httpPost = new HttpPost(WechatPayApiConfig.NATIVE_ORDER);
        httpPost.setHeader("Accept","application/json");
        httpPost.setEntity(entity);

        String result = "";
//        try(CloseableHttpResponse response = wechatPayClient.execute(httpPost)){
//
//            //响应码
//            int statusCode = response.getStatusLine().getStatusCode();
//            //响应体
//            String responseStr = EntityUtils.toString(response.getEntity());
//
//            log.debug("下单响应码:{},响应体:{}",statusCode,responseStr);
//
//            if(statusCode == HttpStatus.OK.value()){
//                JSONObject jsonObject = JSONObject.parseObject(responseStr);
//                if(jsonObject.containsKey("code_url")){
//                    result = jsonObject.getString("code_url");
//                }
//
//            }else {
//                log.error("下单响应失败:{},响应体:{}", statusCode, responseStr);
//            }
//
//        }catch (Exception e){
//            log.error("微信支付响应异常:{}",e);
//        }

        return result;
    }

    @Override
    public String refund(PayInfoVO payInfoVO) {
        return null;
    }

    @Override
    public String queryPayStatus(PayInfoVO payInfoVO) {
        String outTradeNo = payInfoVO.getOutTradeNo();
        String url = String.format(WechatPayApiConfig.NATIVE_QUERY, outTradeNo, payConfig.getMchId());
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "application/json");

        String res = "";

//        try(CloseableHttpResponse response = wechatPayClient.execute(httpGet)){
//            int statusCode = response.getStatusLine().getStatusCode();
//            String responseStr = EntityUtils.toString(response.getEntity());
//            log.debug("查询响应码:{}, 响应体:{}", statusCode, responseStr);
//
//            if(statusCode == HttpStatus.OK.value()) {
//                JSONObject jsonObject = JSONObject.parseObject(responseStr);
//                if (jsonObject.containsKey("trade_state")) {
//                    res = jsonObject.getString("trade_state");
//                    return res;
//                }
//
//            } else {
//                log.error("查询微信支付状态响应失败:{},响应体:{}", statusCode, responseStr);
//            }
//        } catch (Exception e) {
//            log.error("查询微信支付响应异常:{}",e);
//        }
        return res;
    }

    @Override
    public String closeOrder(PayInfoVO payInfoVO) {
        String outTradeNo = payInfoVO.getOutTradeNo();
        JSONObject payObj = new JSONObject();

        String body = payObj.toJSONString();

        log.info("请求参数:{}", body);

        StringEntity entity = new StringEntity(body, "utf-8");

        entity.setContentType("application/json");

        String url = String.format(WechatPayApiConfig.NATIVE_QUERY, outTradeNo, payConfig.getMchId());
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);

        String res = "";

//        try(CloseableHttpResponse response = wechatPayClient.execute(httpPost)){
//            int statusCode = response.getStatusLine().getStatusCode();
//            log.debug("查询响应码:{}, 响应体:{}", statusCode);
//
//            if(statusCode == HttpStatus.OK.value()) {
//               res = "CLOSE_SUCCESS";
//            }
//        } catch (Exception e) {
//            log.error("关闭微信支付响应异常:{}", e);
//        }

        return res;
    }
}
